package com.hyy.lotterysystem.service.Impl;

import com.hyy.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.hyy.lotterysystem.common.exception.ServiceException;
import com.hyy.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir=new File(localPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //创建文件的索引
        String filename = multipartFile.getOriginalFilename();//返回用户上传的原始数据名字
        assert filename != null;

        //获取文件名前缀，作为唯一索引
        String suffix=filename.substring(filename.lastIndexOf("."));
        filename= UUID.randomUUID()+suffix;

        //保存图片
        try {


            multipartFile.transferTo(new File(localPath+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }

        return filename;
    }

}
